<template>
  <div class="modifyDongtai">
    <el-row>
      <el-col :span="24">
        <p class="header-left-title">{{$route.query.cms_id==undefined?'添加动态':'修改动态'}}</p>
      </el-col>
      <el-form ref="form"
               :rules="rules"
               :model="form"
               :inline="true">
        <el-col :span="24"
                class="mid-title">
          <el-col :span="18"
                  id="mid-title-box">
            <el-form-item id="midTile"
                          label="标题"
                          prop="notice_title"
                          label-width="80px"
                          style="width:100%!important;">
              <el-input v-model="form.notice_title"
                        maxlength=20
                        style="width:100%;"></el-input>
            </el-form-item>
            <el-form-item id="midTile"
                          label="所属类目"
                          prop="leimu"
                          label-width="80px"
                          style="width:100%!important;">
              <el-select v-model="form.leimu"
                         placeholder="请选择"
                         style="width:100%"
                         @change="onchange">
                <el-option v-for="item in options"
                           :key="item.code_id"
                           :label="item.name"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item id="midUploadPic"
                          label="封面图片"
                          prop="imgs"
                          v-if="form.is_img=='1'?true:false"
                          label-width="80px"
                          style="width:100%!important;">
              <el-upload class="avatar-uploader"
                         action=""
                         accept=".png,.jpg"
                         :http-request="addUploadPictrue"
                         :show-file-list="false"
                         :on-success="handleAvatarSuccess"
                         :before-upload="beforeAvatarUpload">
                <img v-if="form.imgs"
                     :src="form.imgs"
                     class="avatar">
                <i v-else
                   class="el-icon-plus avatar-uploader-icon"></i>
                <div slot="tip"
                     class="el-upload__tip">支持扩展名：.jpg , .png</div>
              </el-upload>

            </el-form-item>
            <el-form-item id="midPublishContext"
                          label="发布内容"
                          prop="editorContent"
                          label-width="80px"
                          style="width:100%!important;">
              <div class="editor">
                <div ref="toolbar"
                     class="tool_bar">
                </div>
                <div ref="editor"
                     class="mid-editor-box">
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24"
                  id="bottomBox">
            <el-button type="success"
                       @click="onImmediateRelease('form')"
                       id="bottomImmeRelease"
                       v-if="is_release==1?false:true"><span id="bottomReleaseSpan">立即发布</span></el-button>
            <el-button type="primary"
                       @click="onSaveInfo('form')"
                       id="bottomImmeRelease"><span id="bottomSaveSpan">保存</span></el-button>
            <el-button @click="onCancel"><span id="bottomCancelSpan">取消</span></el-button>
          </el-col>
        </el-col>
      </el-form>
    </el-row>
  </div>
</template>
     <script src="https://cdn.bootcss.com/wangEditor/3.1.0/wangEditor.js"></script> 
    <script>
import OSS from 'ali-oss'
import axios from 'axios'
import qs from 'qs'
import E from 'wangeditor'
import { pageComMaintainApi } from "@/services/SystemSetting";
import { standardCodeApi } from '@/services/StandardCode'
export default {
  name: 'editor',
  data () {
    return {
      iops: 0,
      type: '',
      is_release: this.$route.query.is_release,
      cms_id: this.$route.query.cms_id,
      form: {
        editorContent: '',
        cs_time1: '',
        notice_title: '',
        is_img: '1',
        imgs: '',
        imgs_relative: '',
        leimu: '',
      },
      imageUrl: '',
      url_image: '',
      submit_type: '',
      type: '',
      options: [],
      fileList3: [],
      rules: {
        notice_title: [{ required: true, message: '请输入公告标题', trigger: 'blur' }],
        leimu: [{ required: true, message: '是否插入图片', trigger: 'blur' }],
        editorContent: [{ required: true, message: '请输入内容公告', trigger: 'blur' }],
        imgs: [{ required: true, message: '图片不能为空', trigger: 'blur' }],
      }
    }
  },
  methods: {
    seteditor () {
      this.editor = new E(this.$refs.toolbar, this.$refs.editor)
      this.editor.customConfig.uploadImgShowBase64 = false // base 64 存储图片
      this.editor.customConfig.uploadImgServer = ''// 配置服务器端地址
      this.editor.customConfig.uploadImgHeaders = {}// 自定义 header
      this.editor.customConfig.uploadFileName = '' // 后端接受上传文件的参数名
      this.editor.customConfig.uploadImgMaxSize = 2 * 1024 * 1024 // 将图片大小限制为 2M
      this.editor.customConfig.uploadImgMaxLength = 6 // 限制一次最多上传 3 张图片
      this.editor.customConfig.uploadImgTimeout = 3 * 60 * 1000 // 设置超时时间 
      this.editor.customConfig.showLinkImg = false; //隐藏上传网络图片
      //自定义图片上传
      this.editor.customConfig.customUploadImg = async (files, insert) => {
        var _this = this;
        var oss_region = new OSS({
          region: 'oss-cn-hangzhou',
          accessKeyId: this.util.decrypt(process.env.AES_OSS_ID),
          accessKeySecret: this.util.decrypt(process.env.AES_OSS_SECRET),
          bucket: _this.url_image,
        });
        var c = new Date().getMonth() + parseInt(1);
        if (c >= 10) {

        } else {
          c = '0' + c;
        }
        var path = 'upload/images/notice/' + new Date().getFullYear() + c + new Date().getDate() + '/' + new Date().getTime() + Math.floor(Math.random() * 10) + files[0].name.substring(files[0].name.length - 4);
        //alert(path)
        oss_region.multipartUpload(path, files[0], {

        }).then((res) => {
          //添加图片到编辑框中
          if (res.res.requestUrls[0].indexOf("?") != -1) {
            _this.iops = res.res.requestUrls[0].indexOf("?");
            this.editor.cmd.do('insertHTML', "<img  style='width:auto;height:auto;' src=" + res.res.requestUrls[0].substring(0, _this.iops) + " " + "/>")
          } else {
            this.editor.cmd.do('insertHTML', "<img  style='width:auto;height:auto;' src=" + res.res.requestUrls[0] + " " + "/>")
          }

        }).catch((err) => {
          console.log(err)
        });
      },
        this.editor.customConfig.uploadImgHooks = {
        }
      // 配置菜单
      this.editor.customConfig.menus = [
        'head', // 标题
        'bold', // 粗体
        'fontSize', // 字号
        'fontName', // 字体
        'italic', // 斜体
        'underline', // 下划线
        'strikeThrough', // 删除线
        'foreColor', // 文字颜色
        'backColor', // 背景颜色
        'link', // 插入链接
        'list', // 列表
        'justify', // 对齐方式
        'quote', // 引用
        'emoticon', // 表情
        'image', // 插入图片
        'table', // 表格
        //'video', // 插入视频
        'code', // 插入代码
        'undo', // 撤销
        'redo' // 重复
      ]
      //编辑框内容变化
      var editor = new E(this.$refs.toolbar, this.$refs.editor)
      this.editor.customConfig.onchange = (html) => {
        this.form.editorContent = this.editor.txt.html();
      }
      // 创建富文本编辑器
      this.editor.create()
    },
    //上传png和jpg格式图片
    addUploadPictrue (data) {
      var _this = this;
      var oss_region = new OSS({
        region: 'oss-cn-hangzhou',
        accessKeyId: this.util.decrypt(process.env.AES_OSS_ID),
        accessKeySecret: this.util.decrypt(process.env.AES_OSS_SECRET),
        bucket: _this.image_Url,
      });
      var c = new Date().getMonth() + parseInt(1);
      if (c >= 10) {
      } else {
        c = '0' + c;
      }
      var path = 'upload/images/notice/' + new Date().getFullYear() + c + new Date().getDate() + '/' + new Date().getTime() + Math.floor(Math.random() * 10) + data.file.name.substring(data.file.name.length - 4);
      oss_region.multipartUpload(path, data.file, {
      }).then((res) => {
        if (res.res.requestUrls[0].indexOf("?") != -1) {
          _this.iops = res.res.requestUrls[0].indexOf("?");
          _this.form.imgs = res.res.requestUrls[0].substring(0, _this.iops);
        } else {
          _this.form.imgs = res.res.requestUrls[0];
        }
        _this.form.imgs_relative = res.name;
        _this.form.pictrue_daxiao = Math.round(data.file.size / 1024 / 1024) + 'M';
      }).catch((err) => {
        console.log(err)
      });
    },
    //类目改变
    onchange (val) {
      this.options.forEach(ele => {
        if (ele.value == val) {
          this.type = ele.value
        }
      })
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload (file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isLt2M;
    },
    onImmediateRelease (data) {
      this.$confirm('即将发布当前动态，是否继续!', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.submit_type = 1;
        this.$refs[data].validate((valid) => {
          if (valid) {
            //编辑时‘立即发布’执行
            if ((this.$route.query.cms_id != undefined && this.$route.query.is_release != undefined)) {
              pageComMaintainApi.updateDynamic({
                data: {
                  id: this.cms_id,
                  category: this.type,
                  title: this.form.notice_title,
                  img: this.form.imgs_relative,
                  description: '',
                  content: this.form.editorContent,
                  project_id: '',
                  sort: '',
                  is_release: 1,//0是不发布；1是发布
                }
              }).then((res) => {
                if (res.code == 0) {
                  this.$router.push({ path: 'dynamicInforList' })
                }
              }).catch((error) => {
                console.log(error)
              })
              //保存时‘立即发布’执行
            } else {
              pageComMaintainApi.saveInformation({
                data: {
                  category: this.type,
                  title: this.form.notice_title,
                  img: this.form.imgs_relative,
                  description: '',
                  content: this.form.editorContent,
                  project_id: '',
                  sort: '',
                  is_release: 1,//0是不发布；1是发布
                }
              }).then((res) => {
                if (res.code == 0) {
                  this.$router.push({ path: 'dynamicInforList' })
                }
              }).catch((error) => {
                console.log(error)
              });
            }
          } else {
            //console.log('error submit!!');
            return false;
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消发布'
        });
      });
    },
    //保存
    onSaveInfo (data) {
      this.submit_type = 2;
      this.$refs[data].validate((valid) => {
        if (valid) {
          //编辑时“保存”执行
          if ((this.$route.query.cms_id != undefined && this.$route.query.is_release != undefined)) {
            pageComMaintainApi.updateDynamic({
              data: {
                id: this.cms_id,
                category: this.type,
                title: this.form.notice_title,
                img: this.form.imgs_relative,
                description: '',
                content: this.form.editorContent,
                project_id: '',
                sort: '',
                is_release: 0,//0是不发布；1是发布
              }
            }).then((res) => {
              if (res.code == 0) {
                this.$router.push({ path: 'dynamicInforList' })
              }
            }).catch((error) => {
              console.log(error)
            })
            //添加时“保存”时执行
          } else {
            pageComMaintainApi.saveInformation({
              data: {
                category: this.type,
                title: this.form.notice_title,
                img: this.form.imgs_relative,
                description: '',
                content: this.form.editorContent,
                project_id: '',
                sort: '',
                is_release: 0,//0是不发布；1是发布
              }
            }).then((res) => {
              if (res.code == 0) {
                this.$router.push({ path: 'dynamicInforList' })
              }
            }).catch((error) => {
              console.log(error)
            });
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    },
    //返回
    onCancel () {
      this.form.notice_title = '';
      this.form.is_img = '1';
      this.form.imgs = '';
      this.form.editorContent = '';
      this.$router.push({ path: 'dynamicInforList' });
    },
    //详情信息
    getDetailData () {
      if ((this.$route.query.cms_id != undefined && this.$route.query.is_release != undefined)) {
        pageComMaintainApi.getDynamicDetails({
          params: {
            id: this.cms_id
          }
        }).then((res) => {
          this.form.notice_title = res.data.title;
          this.type = res.data.category;
          //所属类目
          this.options.forEach(ele => {
            if (ele.value == res.data.category) {
              this.form.leimu = ele.value;
            }
          });
          this.form.imgs = res.data.img;//图片显示的全路径
          if (this.form.imgs != '' || this.form.imgs != null) {
            var n = (this.form.imgs.split('http://')).length - 1;//出现的次数
            //如果出现两次‘http://’就执行
            if (n == 2) {
              this.find(this.form.imgs, 'http://', 1)
            }
          };
          this.form.imgs_relative = res.data.img_url;//相对路径
          if (this.form.imgs_relative != '' || this.form.imgs_relative != null) {
            if (this.form.imgs_relative.indexOf('upload') != 0) {
              this.form.imgs_relative = this.form.imgs_relative.substring(this.form.imgs_relative.indexOf('upload'))
              // console.log('详情true==this.form.imgs_relative=', this.form.imgs_relative)
            }
          }
          this.editor.cmd.do('insertHTML', res.data.content);
          this.form.editorContent = res.data.content;
        }).catch((error) => {
          console.log(error)
        })
        //添加时进入该页面不执行任务操作
      } else {
      }
    },
    // 获取动态类型标准码
    getStandardCode () {
      standardCodeApi
        .getStandardCodeData({
          data: {
            code_type: "news_type"
          }
        })
        .then(
          res => {
            if (res.data) {
              this.options = res.data.list;
            }
          },
          err => {
            console.log(err);
          }
        );
    },
    find (str, cha, num) {
      var x = str.indexOf(cha);
      for (var i = 0; i < num; i++) {
        x = str.indexOf(cha, x + 1);
      }
      var img = "http://dev-hibuilding-new.oss-cn-hangzhou.aliyuncs.com/http://dev-hibuilding-new.oss-cn-hangzhou.aliyuncs.com/upload/images/notice/20191029/15723170069177.jpg";
      this.form.imgs = this.form.imgs.substring(x)
      //console.log('location=', x, 'img=', img.substring(x))
    }
  },
  mounted () {
    this.seteditor();
  },
  created () {
    // var img = "http://dev-hibuilding-new.oss-cn-hangzhou.aliyuncs.com/http://dev-hibuilding-new.oss-cn-hangzhou.aliyuncs.com/upload/images/notice/20191029/15723170069177.jpg";

    // if (img != '') {
    //   var n = (img.split('http://')).length - 1;//出现的次数
    //   if (n == 2) {
    //     console.log('location=', this.find(img, 'http://', 1))
    //   }
    // }

    // 获取动态类型标准码
    this.getStandardCode();
    //判断是否是编辑的状态，如果是编辑的话就给赋值显示出来
    if ((this.$route.query.cms_id != undefined && this.$route.query.is_release != undefined)) {
      //获取详情数据
      this.getDetailData();
      //添加动态时啥也不执行
    } else {

    }
    if (location.hostname === 'localhost') {
      this.image_Url = 'dev-hibuilding-new'
    } else if (location.hostname.split('.')[1] === 'ihibuilding') {
      this.image_Url = 'dev-hibuilding-new'
    } else if (location.hostname.split('.')[1] === 'hibuilding') {
      this.image_Url = 'hibuilding'
    }
    //富文本编辑器图片上传oss路径配置
    if (location.hostname === 'localhost') {
      this.url_image = 'dev-hibuilding-new'
    } else if (location.hostname.split('.')[1] === 'ihibuilding') {
      this.url_image = 'dev-hibuilding-new'
    } else if (location.hostname.split('.')[1] === 'hibuilding') {
      this.url_image = 'hibuilding'
    }
  }
}
</script>
<style lang="scss" scoped>
.mid-title {
  margin-top: 20px;
}
.header-left-title {
  font-size: 18px;
  font-family: SimSun;
  font-weight: 400;
  color: rgba(20, 65, 179, 1);
}
#bottomCancelSpan {
  width: 70px !important;
  display: block;
  height: 36px;
  line-height: 36px;
  text-align: center;
}
#bottomSaveSpan {
  width: 70px !important;
  display: block;
  height: 36px;
  line-height: 36px;
  text-align: center;
}
#bottomReleaseSpan {
  width: 92px !important;
  display: block;
  height: 36px;
  line-height: 36px;
  text-align: center;
}
#bottomImmeRelease {
  margin-right: 20px;
}
#bottomBox {
  margin-top: 0px;
  text-align: center;
  margin-bottom: 20px;
  /deep/ button {
    -webkit-appearance: button;
    height: 36px;
    padding: 0px;
  }
}
#midPublishContext {
  /deep/ .w-e-text-container {
    position: relative;
    z-index: 0 !important;
  }
  /deep/ .el-form-item__content {
    line-height: 40px;
    position: relative;
    font-size: 14px;
    width: auto !important;
  }
}
/deep/ .tool_bar {
  border: 1px solid #ccc;
}
.mid-editor-box {
  border: 1px solid #ccc;
  height: 600px;
}
.modifyDongtai {
  .el-form-item__content {
    line-height: 40px;
    position: relative;
    font-size: 14px;
    width: 90% !important;
  }
  padding: 10px 20px !important;
  background: #ffffff;
}
#midTile {
  /deep/ .el-form-item__content {
    line-height: 40px;
    position: relative;
    font-size: 14px;
    width: 50% !important;
  }
}
#mid-title-box {
  /deep/ .el-form-item__label {
    text-align: right;
    float: left;
    font-size: 14px;
    color: #606266;
    line-height: 40px;
    padding: 0 12px 0 0;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
  }
}
#midUploadPic {
  /deep/ .el-upload__tip {
    font-size: 12px;
    color: #606266;
    margin-top: -10px;
  }
  /deep/ .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  /deep/ .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  /deep/ .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  /deep/ .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
/deep/ .editor {
  width: 100% !important;
}
/deep/ .el-form--inline .el-form-item {
  display: flex !important;
}
.info {
  border-radius: 10px;
  line-height: 20px;
  padding: 10px;
  margin: 10px;
  background-color: #ffffff;
}
</style>